package com.zndroid.upgrader.db;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class DBTaskImpl implements IDBTaskListener {
    DBHelper helper;

    public DBTaskImpl(Context context) {
        helper = new DBHelper(context, DBHelper.DB_NAME, null,
                DBHelper.VERSION);
    }

    @Override
    public void insertTask(TaskInfo taskInfo) {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL(
                "insert into " + DBHelper.TABLE_NAME + "(url, start, size) values(?,?,?)",
                new Object[] {taskInfo.getUrl(),
                        taskInfo.getStartIndex(), taskInfo.getFileSize()});
        db.close();
    }

    @Override
    public void deleteTask(String url) {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("delete from " + DBHelper.TABLE_NAME + " where url = ?",
                new Object[] { url});
        db.close();
    }

    @Override
    public void updateTask(String url, long finished, long fileSize) {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL(
                "update " + DBHelper.TABLE_NAME + " set start = ? , size = ? where url = ?",
                new Object[] { finished, fileSize, url});
        db.close();
    }

    @Override
    public TaskInfo getTask(String url) {
        TaskInfo taskInfo = new TaskInfo();
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from " + DBHelper.TABLE_NAME + " where url = ?",
                new String[] { url });
        if (cursor.moveToFirst()) {
            taskInfo.setFileSize(cursor.getLong(cursor.getColumnIndex("size")));
            taskInfo.setUrl(cursor.getString(cursor.getColumnIndex("url")));
            taskInfo.setStartIndex(cursor.getLong(cursor.getColumnIndex("start")));
        }
        db.close();
        cursor.close();
        return taskInfo;
    }

    @Override
    public boolean isTaskExists(String url) {
        boolean isExists;
        SQLiteDatabase db = helper.getWritableDatabase();
        Cursor cursor = db.rawQuery(
                "select * from " + DBHelper.TABLE_NAME + " where url = ?",
                new String[] {url});

        isExists = cursor.moveToFirst();
        db.close();
        cursor.close();
        return isExists;
    }
}
